<template>
	<view class="address">
		<!-- <view class="address-item" v-for="item in addressList" :key="item.id"> -->
			<u-swipe-action class="address-item" v-for="(item,index) in addressList" :key="item.id">
				<u-swipe-action-item :options="options" @click="swipeClick(item.id, index, $event)">
					<u-cell class="address" :label="item.address">
						<view slot="title" class="u-slot-title" @click="addressSelect(item.id)">
							<text class="u-cell-text">{{item.name+' '+item.phone}}</text>
							<u-tag text="默认" size="mini" type="error" :show="item.is_default===1"></u-tag>
						</view>
						<u-icon slot="value" name="edit-pen" size="50rpx" @click="editAddress(item)"></u-icon>
					</u-cell>
				</u-swipe-action-item>
			</u-swipe-action>
		<!-- </view> -->
		<view class="add-address">
			<u-button class="submit" type="error" shape="circle" text="+ 新建收货地址" size="normal" @click="addAddress"></u-button>
		</view>
	</view>
</template>

<script>
	export default {
		data() {
			return {
				addressList: [],
				options: [
					{
						text: '设置默认',
						style: {
								backgroundColor: '#3c9cff'
						}
					},
					{
						text: '删除',
						style: {
								backgroundColor: '#f56c6c'
						}
					},
				],
			}
		},
		onLoad() {
			this.getOrders()
		},
		methods: {
			async getOrders() {
				const res = await uni.$u.http.get('/api/orders/preview')
				console.log(res)
				this.addressList = res.address
				console.log(this.addressList)
			},
			// 选择地址
			addressSelect(id) {
				// 判断上级路径是否是从profile中进入
				let page = getCurrentPages()
				page = page[page.length-2]?.route
				if (page === 'pages/profile/profile') return
				console.log(page)
				// 保存地址ID到storage中
				uni.setStorageSync('address_id',id)
				// 跳回到订单页面
				uni.$u.route({
					url: 'pages/cart/order',
				})
			},
			// 左滑操作
			swipeClick(id, i, params) {
				if (params.index === 0) {
					// 将地址设置为默认
					uni.$u.http.patch(`/api/address/${id}/default`)
					// 更改默认图标
					this.addressList.map((item, j) => {
						if (i === j) {
							item.is_default = 1
						}else {
							item.is_default = 0
						}
					})
				}else {
					// 删除地址
					uni.$u.http.delete(`/api/address/${id}`)
					// 删除对应addressList中的元素
					this.addressList.splice(i, 1)
				}
			},
			// 编辑地址
			editAddress(data) {
				// 将当前地址数据保存在vuex中
				this.$u.vuex('vuex_address', data)
				// 路由跳转到地址编辑页面
				uni.$u.route({
					url: '/pages/profile/address/edit_address'
				})
			},
			// 添加地址
			addAddress() {
				this.$u.vuex('vuex_address', null)
				// 路由跳转到地址编辑页面
				uni.$u.route({
					url: '/pages/profile/address/edit_address'
				})
				
			}
		}
	}
</script>

<style lang="scss" scoped>
.address {
	.address-item {
		.u-slot-title {
			display: flex;
			.u-cell-text {
				margin-right: 20rpx;
			}
		}
	}
	.add-address {
		position: fixed;
		bottom: 0;
		width: 750rpx;
		.submit {
			width: 710rpx;
			margin: 20rpx;
		}
	}
}
</style>
